from common.utils.rights import permission_required, view_logging_required
from common.utils.file_read import file_read
from . import index_bp
from flask import render_template,request
from flask_wtf.form import CombinedMultiDict
from models.form import UploadForm
import cv2 as cv
import numpy as np


def imgCorrode(img, x, y):  # x、y控制核的大小
    kernel = np.ones((x, y), np.uint8)
    img_corrode = cv.erode(img, kernel)
    return img_corrode


@index_bp.get('/corrode_pro')
@index_bp.post('/corrode_pro')
@view_logging_required
@permission_required("corrode:pro")
def corrode_pro():
    if request.method == "GET":
        return render_template('admin/cv/corrode.html')
    else:
        form = UploadForm(CombinedMultiDict([request.form, request.files]))
        if form.validate():
            f = request.files['file']
            file_url = file_read(f)
            pic = cv.imread(file_url)
            kernel_x = int(request.form.get('kx'))
            kernel_y = int(request.form.get('ky'))
            out_image = imgCorrode(pic,kernel_x,kernel_y)
            res_pic = "static/download/corrode.jpg"
            cv.imwrite(res_pic,out_image)
            return render_template('admin/cv/corrode.html', pic=file_url, res_pic=res_pic)
        else:
            return "请传入正确的文件格式"
